package com.tianma315.core.common.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.tianma315.core.common.domain.ConfigDO;
import com.tianma315.core.common.service.ConfigService;
import com.tianma315.core.common.utils.HttpJsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @author lgc
 * @createDate 2020/6/18 - 11:36
 */
@Service
public class ScheduledService {

    @Autowired
    private ConfigService configService;
    /**
     * 定时获取萤石accessToken
     */

//    @Scheduled(cron = "0 * * * * MON-FRI")
    @Scheduled(cron = "0 0 0 ? * MON")//每月的周一
    public void getAccessToken(){
        String yishi = configService.getValuByKey("yishi");
        JSONObject jsonObject = JSONObject.parseObject(yishi);
        String appKey = (String)jsonObject.get("appKey");
        String appSecret = (String)jsonObject.get("appSecret");
        String accessTokens = getAccessToken(appKey, appSecret);
        System.out.println(accessTokens);
        if (!accessTokens.isEmpty()){
             ConfigDO accessTonken = configService.getByKey("accessToken");
                accessTonken.setV(accessTokens);
                accessTonken.setCreateTime(new Date());
                configService.updateById(accessTonken);
        }
        System.out.println("获取完毕");
    }

   String getAccessToken (String appkey,String secret){

       String url = "https://open.ys7.com/api/lapp/token/get";
       HashMap<String, String> map = new HashMap<>();
       map.put("appKey",appkey);
       map.put("appSecret",secret);
       String post = null;//获取返回数据（含有AccessToken等数据）
       String accessToken = null;
       try {
           post = HttpJsonUtils.post(url, map);
       } catch (IOException e) {
           e.printStackTrace();
       }
       if (post==null){
           return null;
       }
       JSONObject jsonObject = JSONObject.parseObject(JSONObject.parseObject(post).getString("data"));
       accessToken = jsonObject.getString("accessToken");
       return accessToken;
   }
}
